//--------------------------------------------------------------
//
// Qizhi Zhang 
// ezhung@gmail.com
// http://www.moorwind.com
//
//--------------------------------------------------------------
package reader.controller
{
	import org.puremvc.as3.multicore.interfaces.ICommand;
	import org.puremvc.as3.multicore.interfaces.INotification;
	import org.puremvc.as3.multicore.patterns.command.SimpleCommand;
	
	import reader.core.ReaderModelLocator;
	import reader.core.WindowManager;
	import reader.events.ExternalAuthPanelEvent;
	import reader.model.vo.ServiceVO;
	import reader.view.components.ExternalAuthPanel;

	public class OpenAuthCommand extends SimpleCommand implements ICommand
	{
		////////////////////////////////////////////////////////////////////////////////
		//private variables
		
		private var callback:Function;
		
		//////////////////////////////////////////////////////////////////////////////
		//methods
				
		override public function execute(notification:INotification):void
		{
			var window:ExternalAuthPanel;
			if(!WindowManager.isWindowRegisted(ReaderModelLocator.WINDOW_OAUTH_PANEL))
			{
				callback = notification.getBody().callback as Function;
				window = new ExternalAuthPanel();
				window.windowType = ReaderModelLocator.WINDOW_OAUTH_PANEL;
				initializeWindow(ServiceVO(notification.getBody().service), window);
				WindowManager.registerWindow(window);
				window.addEventListener(ExternalAuthPanelEvent.HTML_FLAG_PAGE, onFlagPage_handler);
				window.open();
			}
			else
			{
				window = WindowManager.getRegisterWindow(ReaderModelLocator.WINDOW_OAUTH_PANEL) as ExternalAuthPanel;
				if(!window) return;
				callback = notification.getBody().callback as Function;
				initializeWindow(ServiceVO(notification.getBody().service), window);
				window.addEventListener(ExternalAuthPanelEvent.HTML_FLAG_PAGE, onFlagPage_handler);
				window.nativeWindow.orderToFront();
			}
		}
		
		private function initializeWindow(service:ServiceVO, window:ExternalAuthPanel):void
		{
			window.HTMLlocation = service.login_url;
			window.HTMLFlag = service.login_flag;
			window.width = service.login_width;
			window.height = service.login_height;
			window.HTMLCallback = ReaderModelLocator.instance.adCallBack;
		}
		
		private function onFlagPage_handler(e:ExternalAuthPanelEvent):void
		{
			var window:ExternalAuthPanel = e.currentTarget as ExternalAuthPanel;
			window.removeEventListener(ExternalAuthPanelEvent.HTML_FLAG_PAGE, onFlagPage_handler);
			callback(e.url);
			callback = null;
		}
		
	}
}